package com.tools.scanner.ui.history

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.tools.scanner.BaseActivity
import com.tools.scanner.R
import com.tools.scanner.constant.AdLocationConstant
import com.tools.scanner.ad.AdManager
import com.tools.scanner.databinding.ActivityHistoryBinding
import com.tools.scanner.ui.history.fragment.BaseHistoryFragment
import com.tools.scanner.ui.history.fragment.CreateHistoryFragment
import com.tools.scanner.ui.history.fragment.DocumentHistoryFragment
import com.tools.scanner.ui.history.fragment.ScannerHistoryFragment

class HistoryActivity : BaseActivity() {

    companion object {
        fun actionStart(context: Context) {
            val intent = Intent(context, HistoryActivity::class.java)
            context.startActivity(intent)
        }
    }

    private lateinit var mBinding: ActivityHistoryBinding
    private val mAdLocation = AdLocationConstant.N_HISTORY

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = ActivityHistoryBinding.inflate(layoutInflater)
        setContentView(mBinding.root)

        AdManager.subscribeAdLoadStatusEvent(mAdLocation, this) {
            if (it.status == AdManager.AdLoadStatus.SUCCESS) {
                showNativeAd()
            }
        }
        AdManager.loadNativeAd(mAdLocation)
        AdManager.addStepCount(mAdLocation)

        mBinding.ivBack.setOnClickListener {
            finish()
        }

        mBinding.tabLayout.apply {
            addTab(newTab())
            addTab(newTab())
            addTab(newTab())

            val listener = object : TabLayout.OnTabSelectedListener {
                override fun onTabSelected(tab: TabLayout.Tab) {

                }

                override fun onTabUnselected(tab: TabLayout.Tab) {

                }

                override fun onTabReselected(tab: TabLayout.Tab) {}
            }

            addOnTabSelectedListener(listener)

            getTabAt(0)?.let {
                listener.onTabSelected(it)
            }
        }

        mBinding.viewPager.offscreenPageLimit = 3
        mBinding.viewPager.adapter = object : FragmentStateAdapter(this) {
            override fun getItemCount(): Int {
                return 3
            }

            override fun createFragment(position: Int): Fragment {
                if (position == 0) {
                    return ScannerHistoryFragment()
                }
                if (position == 1) {
                    return CreateHistoryFragment()
                }
                if (position == 2) {
                    return DocumentHistoryFragment()
                }

                throw RuntimeException()
            }
        }

        TabLayoutMediator(mBinding.tabLayout, mBinding.viewPager) { tab, position ->
            when (position) {
                0 -> {
                    tab.setText(R.string.tab_scanner)
                }

                1 -> {
                    tab.setText(R.string.tab_creator)
                }

                else -> {
                    tab.setText(R.string.tab_document)
                }
            }
        }.attach()

        mBinding.editText.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            }

            override fun afterTextChanged(s: Editable?) {
                getCurrentFragment()?.let {
                    if (it.isAdded) {
                        it.search(s.toString())
                    }
                }
            }
        })
    }

    private fun getCurrentFragment(): BaseHistoryFragment? {
        val currentPosition = mBinding.viewPager.currentItem
        val adapter = mBinding.viewPager.adapter as? FragmentStateAdapter ?: return null
        val itemId = adapter.getItemId(currentPosition)
        val fragment = supportFragmentManager.findFragmentByTag("f$itemId")
        return if (fragment is BaseHistoryFragment) {
            fragment
        } else {
            null
        }
    }

    private fun showNativeAd() {
        val nativeAdView = AdManager.getNativeAdView(mAdLocation) ?: return

        mBinding.flAdContainer.removeAllViews()
        mBinding.flAdContainer.addView(nativeAdView)
    }

}